package io.nutz.nutzsite.module.job.controller;

import io.nutz.nutzsite.common.base.Result;
import io.nutz.nutzsite.common.utils.DateUtils;
import io.nutz.nutzsite.common.utils.IpUtils;
import io.nutz.nutzsite.common.utils.ShiroUtils;
import io.nutz.nutzsite.module.job.models.Jobed;
import io.nutz.nutzsite.module.job.models.Jobpub;
import io.nutz.nutzsite.module.job.services.JobedService;
import io.nutz.nutzsite.module.job.services.JobpubService;
import io.nutz.nutzsite.module.sys.models.User;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.codec.binary.Base64;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Lang;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.POST;
import org.nutz.mvc.annotation.Param;
import org.nutz.plugins.slog.annotation.Slog;
/**
 * 已交作业 信息操作处理
 * 
 * @author lrw
 * @date 2020-03-06
 */
@IocBean
@At("/job/sned")
public class JobedController {
	private static final Log log = Logs.get();

	@Inject
	private JobedService jobedService;
	@Inject
	private JobpubService jobpubService;
	
	@RequiresPermissions("job:sned:view")
	@At("/detail/?")
	@Ok("th:/job/sned/sned.html")
	public void index(String snid,HttpServletRequest req) {
		req.setAttribute("snid", snid);
		Jobpub jobpub=jobpubService.fetch(snid);
		req.setAttribute("title",jobpub.getTitle());
	}
	@RequiresPermissions("job:sned:view")
	@At
	@Ok("th:/job/front/sned.html")
	public void myjobs(HttpServletRequest req) {
		req.setAttribute("now0", DateUtils.getDateTime());
	}
	/**
	 * 查询已交作业列表
	 */
	@RequiresPermissions("job:sned:list")
	@At
	@Ok("json")
	public Object list(@Param("pageNum")int pageNum,
					   @Param("pageSize")int pageSize,
					   @Param("snid")String snid,
					   @Param("orderByColumn") String orderByColumn,
					   @Param("isAsc") String isAsc,
					   HttpServletRequest req) {
		Cnd cnd = Cnd.NEW();
		cnd.and("snid", "=", snid);
		return jobedService.tableList(pageNum,pageSize,cnd,orderByColumn,isAsc,null);
	}
	//查看属于我自己的作业任务
		@RequiresPermissions("job:sned:list")
		@At
		@Ok("json")
		public Object list2(@Param("pageNum")int pageNum,
						   @Param("pageSize")int pageSize,
						   @Param("orderByColumn") String orderByColumn,
						   @Param("isAsc") String isAsc,
						   HttpServletRequest req) {
			Cnd cnd = Cnd.NEW();
			cnd.and("uid", "=", ShiroUtils.getSysUserId());
			return jobedService.tableList(pageNum,pageSize,cnd,orderByColumn,isAsc,"snpub");
		}
		/**
		 * 查询编译错误信息
		 */
		@At
		@Ok("th:/jobcontent.html")
		public void myjob(@Param("id") int id, HttpServletRequest req) {
			Jobed solutionSource=jobedService.fetch(id);
			//String ceinfo=solutionSource.getContent();
			req.setAttribute("sned", solutionSource);
		}		
	/**
	 * 新增已交作业
	 */
	@At("/add")
	@Ok("th:/job/sned/add.html")
	public void add( HttpServletRequest req) {

	}

	/**
	 * 新增保存已交作业
	 */
	@At
	@POST
	@Ok("json")
	@RequiresPermissions("job:sned:add")
	@Slog(tag="已交作业", after="新增保存已交作业 id=${args[0].id}")
	public Object addDo(@Param("..") Jobed sned,HttpServletRequest req) {
		try {
			jobedService.insert(sned);
			return Result.success("system.success");
		} catch (Exception e) {
			return Result.error("system.error");
		}
	}

	/**
	 * 修改已交作业
	 */
	@At("/edit/?")
	@Ok("th://job/sned/edit.html")
	public void edit(String id, HttpServletRequest req) {
		Jobed sned = jobedService.fetch(id);
		req.setAttribute("sned",sned);
	}

	/**
	 * 修改保存已交作业
	 */
	@At
	@POST
	@Ok("json")
	@RequiresPermissions("job:sned:edit")
	@Slog(tag="已交作业", after="修改保存已交作业")
	public Object editDo(@Param("..") Jobed sned,HttpServletRequest req) {
		try {
			if(Lang.isNotEmpty(sned)){
				jobedService.update(sned);
			}
			return Result.success("system.success");
		} catch (Exception e) {
			return Result.error("system.error");
		}
	}

	/**
	 * 删除已交作业
	 */
	@At("/remove")
	@Ok("json")
	@RequiresPermissions("job:sned:remove")
	@Slog(tag ="已交作业", after= "删除已交作业:${array2str(args[0])}")
	public Object remove(@Param("ids")String[] ids, HttpServletRequest req) {
		try {
			jobedService.delete(ids);
			return Result.success("system.success");
		} catch (Exception e) {
			return Result.error("system.error");
		}
	}
	/**
	 * 修改作业
	 */
	@At("/edit2")
	@Ok("json")
	@POST
	@RequiresPermissions("job:sned:edit")
	@Slog(tag="提交作业", after="修改保存作业")
	public Object edit2( @Param("..") Jobed jobed, HttpServletRequest req) {
		
		try {
			String snid=jobed.getSnid();
			String content=new String(new Base64().decode(jobed.getContent()), "UTF-8");
			Jobed sned = jobedService.fetch(Cnd.where("snid", "=", snid).and("uid", "=", ShiroUtils.getSysUserId()));
			if(sned.getScore()>0) return Result.error("已批改，不允许再提交。");
			sned.setSnip(IpUtils.getIpAddr(req));
			sned.setSntime(new Date());
			sned.setContent(content);
			sned.setComment("待阅");
			Jobpub snpub=jobpubService.fetch(Cnd.where("id", "=", snid));
			
			
			//Date t1=snpub.getSnstarttime();
			if(snpub.isHasendtime()) {
				Date t2=snpub.getSnendtime();
				Date t0=new Date();
				if(t2.getTime()<t0.getTime()){//若迟到，记录迟到分钟数
					int d=(int)DateUtils.getDistanceOfTwoDate(t2, t0, "m");
					sned.setStatus(d);
					jobedService.update(sned);
				}else {
					sned.setStatus(0);//签到进行中
					jobedService.update(sned);
				}
				
			}else {
				sned.setStatus(0);//手工没结束,签到进行中
				jobedService.update(sned);
			}

			int absentsn=jobedService.count(Cnd.where("snid", "=", snid).and("status", "=", -1));
			int ontimesn=jobedService.count(Cnd.where("snid", "=", snid).and("status", "=", 0));
			int latesn=jobedService.count(Cnd.where("snid", "=", snid).and("status", ">", 0));
			jobpubService.update(Chain.make("ontimesn", ontimesn).add("latesn", latesn).add("absentsn", absentsn),Cnd.where("id", "=", snid));

			return Result.success("system.success");
		} catch (Exception e) {
			e.printStackTrace();
			return Result.error("system.error");
		}
	}
	/**
	 * 批阅作业
	 */
	@At("/edit3")
	@Ok("json")
	@POST
	@RequiresPermissions("job:sned:edit3")
	@Slog(tag="批阅作业", after="批阅作业")
	public Object edit3( @Param("..") Jobed jobed, HttpServletRequest req) {
		String user=ShiroUtils.getSysUserId();
		try {
			int id=jobed.getId();
			int score=jobed.getScore();
			Jobed sned = jobedService.fetch(id);
			sned.setIsrejob(jobed.isIsrejob());
			sned.setComment(jobed.getComment());
			sned.setScore(score);
			sned.setCheckby(user);
			sned.setChecktime(new Date());
			jobedService.update(sned);
			return Result.success("system.success");
		} catch (Exception e) {
			e.printStackTrace();
			return Result.error("system.error");
		}
	}
}
